package com.kushuigu.controller;

import com.kushuigu.domain.Book;
import com.kushuigu.exception.BusinessException;
import com.kushuigu.exception.SystemException;
import com.kushuigu.hp.Code;
import com.kushuigu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        try{
            if (id == 96) {
                throw new BusinessException("business",Code.BUSINESS_ERR);
            }
        }catch (Exception e){
            throw new SystemException("SYSTEM",e,Code.SYSTEM_UNKNOWN_ERR);
        }
        Book book = bookService.getById(id);
        return new Result(book,
                book == null ? Code.GET_ERR : Code.GET_OK,
                book == null ? "no result" : "ok");
    }

    @GetMapping
    public Result getAll() {
        List<Book> list = bookService.getAll();
        return new Result(list,
                list == null ? Code.GET_ERR : Code.GET_OK,
                list == null ? "no result" : "ok");
    }

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean ret = bookService.save(book);
        return new Result(ret, ret ? Code.SAVE_OK : Code.SAVE_ERR);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean ret = bookService.update(book);
        return new Result(ret, ret ? Code.UPDATE_OK : Code.UPDATE_ERR);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean ret = bookService.delete(id);
        return new Result(ret, ret ? Code.DELETE_OK : Code.DELETE_ERR);
    }

}

